package com.globallogic.dailyplanner.jsfbeans;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.globallogic.dailyplanner.dto.Mail;
import com.globallogic.dailyplanner.ejb.MailServiceBean;
import com.globallogic.dailyplanner.service.MailService;

@Controller
@ManagedBean(name="mailSenderBean")
public class MailSenderBean {
	private static final FacesMessage INFO_MESSAGE = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", "Your mail were sended.");
	private static final FacesMessage ERROR_MESSAGE = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Problem while sending the mail.");

	@Autowired
	private MailService mailService;
	
	@EJB(mappedName = "java:module/MailServiceBean")
	private MailServiceBean mailServiceBean;
	
	private String[] selectedUsers;
	private Mail mail;
	
	public void sendMessages(){
		mailService.save(mail);
		boolean isSended = mailServiceBean.sendMessage(selectedUsers, mail);
		
		FacesContext context = FacesContext.getCurrentInstance();
		
		if(isSended) {
			context.addMessage(null, INFO_MESSAGE);
		} else {
			context.addMessage(null, ERROR_MESSAGE);
		}
	}

	public String[] getSelectedUsers() {
		return selectedUsers;
	}

	public void setSelectedUsers(String[] selectedUsers) {
		this.selectedUsers = selectedUsers;
	}

	public Mail getMail() {
		if(mail == null) mail = new Mail();
		return mail;
	}

	public void setMail(Mail mail) {
		this.mail = mail;
	}
}
